package com.promise.jokerdream.ui.webview

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.webkit.CookieManager
import android.webkit.WebSettings
import android.webkit.WebView
import com.promise.jokerdream.utils.FontSizePreferenceManager

object WebViewFactory {
	private const val TAG = "WebViewFactory"

	/**
	 * 清除所有Cookie
	 */
	fun clearAllCookies() {
		try {
			val cookieManager = CookieManager.getInstance()
			cookieManager.removeAllCookies(null)
			cookieManager.flush()
			Log.d(TAG, "已清除所有Cookie")
		} catch (e: Exception) {
			Log.e(TAG, "清除Cookie失败: ${e.message}")
		}
	}


	/**
	 * 应用字体大小设置到 WebView
	 */
	fun applyFontSize(webView: WebView, context: Context) {
		webView.settings.textZoom = FontSizePreferenceManager.getFontSize(context)
	}
	
	@SuppressLint("SetJavaScriptEnabled")
	fun createWebView(context: Context, callback: IWebViewCallback): WebView {
		return WebView(context).apply {

            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )

			// 开启 WebView 调试（方便查看 console 与网络请求）
			WebView.setWebContentsDebuggingEnabled(true)

			settings.apply {
				// 启用 JavaScript 与窗口自动打开
				javaScriptEnabled = true
				javaScriptCanOpenWindowsAutomatically = true

				// 文件与内容访问
				allowFileAccess = true
				allowContentAccess = true

				useWideViewPort = true
				loadWithOverviewMode = true

				// 存储与缓存
				domStorageEnabled = true
				cacheMode = WebSettings.LOAD_DEFAULT

				// 媒体自动播放
				mediaPlaybackRequiresUserGesture = false

				// 资源与安全策略
				mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

				// 缩放
				setSupportZoom(false)
				builtInZoomControls = true
				displayZoomControls = false

				// 使用系统默认 UA，避免 UA 误判导致功能降级
				userAgentString = WebSettings.getDefaultUserAgent(context)
				// 打印当前 UA 以定位 UA 分类问题
				Log.d(TAG, "当前 WebView UA: $userAgentString")

                safeBrowsingEnabled = true
				
				// 应用保存的字体大小设置
				textZoom = FontSizePreferenceManager.getFontSize(context)
			}

			// 启用硬件加速
			setLayerType(View.LAYER_TYPE_HARDWARE, null)

			// 允许第三方 Cookie（某些登录控件依赖）
			try {
				CookieManager.getInstance().setAcceptCookie(true)
				CookieManager.getInstance().setAcceptThirdPartyCookies(this, true)
			} catch (t: Throwable) {
				Log.w(TAG, "设置 Cookie 失败: ${t.message}")
			}

			webViewClient = CustomWebViewClient(
				context = context,
				callback = callback
			)

			webChromeClient = CustomWebChromeClient(
				callback = callback
			)
		}
	}
}